package edu.ptu.communityplatform.interceptor;

import edu.ptu.communityplatform.common.controller.AjaxResponse;
import edu.ptu.communityplatform.utils.JWTUtil;
import edu.ptu.communityplatform.utils.ResponseUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @BelongsProject: communityPlatform
 * @BelongsPackage: edu.ptu.communityplatform.interceptor
 * @Author: HYJ
 * @CreateTime: 2025-04-05  00:33
 * @Description: 权限验证拦截器，用于检查请求头中的JWT token
 * @Version: 1.0
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {
    /**
     * 前置拦截方法，验证请求头中的token有效性
     *
     * @param request  HTTP请求对象
     * @param response HTTP响应对象
     * @param handler  被拦截的处理器对象
     * @return 验证通过返回true，否则返回false
     * @throws Exception 可能抛出JWT验证相关异常
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头中的token
        String token = request.getHeader("token");
        // 验证token
        if (token == null || !JWTUtil.verifyToken(token)) {
            // 验证失败，返回401
            response.setContentType("application/json;charset=utf-8");

            // 响应失败信息
            ResponseUtil.toResponse(response, new AjaxResponse(401, "token验证失败", null));
            return false;
        }
        return true;
    }
}
